﻿using System;

using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace IFD2
{
    public partial class ExchRate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["ACL"].ToString().IndexOf("FE1") < 0)
                {
                    Response.Redirect("unauthorized.aspx");
                }
            }
            btnAdd.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            btnUpdate.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            btnDelete.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
        }

        protected void lbtnQuery_Click(object sender, EventArgs e)
        {
            GridView1.DataBind();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("FE2") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            int ret_code;
            string key;
            string[] strArray;
            if (Request.Form["KEY"] == null)
            {
                lblError.Text = "Please select the record.";
                return;
            }
            key = Request.Form["KEY"];
            strArray = key.Split('|');

            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_exchrate_delete";
                SqlParameter para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@exch_from", strArray[0]);
                para = cmd.Parameters.AddWithValue("@exch_to", strArray[1]);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblError.Text = "Done.";
                    GridView1.DataBind();
                }
                else
                    lblError.Text = "Unknow Error(" + ret_code.ToString() + ")";
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }


        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("FE2") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            int ret_code;


            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_exchrate_add";
                SqlParameter para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@exch_from", lstCurrFrom.SelectedValue);
                para = cmd.Parameters.AddWithValue("@exch_to", lstCurrTo.SelectedValue);
                para = cmd.Parameters.AddWithValue("@exch_rate", txtRate.Text);
                para.DbType = DbType.Decimal;
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblError.Text = "Done.";
                    GridView1.DataBind();
                }
                else
                    lblError.Text = "Unknow Error(" + ret_code.ToString() + ")";
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }


        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("FE2") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }
            int ret_code;
            string key;
            string[] strArray;
            if (Request.Form["KEY"] == null)
            {
                lblError.Text = "Please select the record.";
                return;
            }
            key = Request.Form["KEY"];
            strArray = key.Split('|');

            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_exchrate_set";
                SqlParameter para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@exch_from", strArray[0]);
                para = cmd.Parameters.AddWithValue("@exch_to", strArray[1]);
                para = cmd.Parameters.AddWithValue("@exch_rate", txtRate2.Text);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblError.Text = "Done.";
                    GridView1.DataBind();
                }
                else
                    lblError.Text = "Unknow Error(" + ret_code.ToString() + ")";
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }


        }
        protected void btnImport_Click(object sender, EventArgs e)
        {
            lblError2.Text = "";
            if (Session["ACL"].ToString().IndexOf("FE3") < 0)
            {
                lblError2.Text = "Unauthorized!";
                return;
            }

            if (!FileUpload1.HasFile || System.IO.Path.GetExtension(FileUpload1.FileName).ToLower() != ".csv")
            {
                lblError2.Text = "Please select CSV file first!";
                return;
            }
            if (FileUpload1.PostedFile.ContentLength < 20 || FileUpload1.PostedFile.ContentLength > 50000)//50000B约可容纳50种货币全排列兑换率（2500行，20B/行）
            {
                lblError2.Text = "The file is empty or larger than 50KB!";
                return;
            }
            int line_num = 1, ret_code;
            string[] strArray;
            StreamReader sr = new StreamReader(this.FileUpload1.PostedFile.InputStream);

            //检查标题行：FROM,TO,RATE
            string line = sr.ReadLine();
            if (line == null)
            {
                sr.Close();
                lblError2.Text = "The file is empty!";
                return;
            }
            string IP = Request.UserHostAddress.ToString();
            string User = Session["USER"].ToString();
            string Airline = Session["AIRLINE"].ToString();
            line = line.ToUpper().Replace('\t', ',');//将"TAB"替换为","
            strArray = line.Split(',');
            if (strArray.Length != 3)
            {
                sr.Close();
                lblError2.Text = "Invalid file header!";
                return;
            }
            if (strArray[0] != "FROM" || strArray[1] != "TO" || strArray[2] != "RATE")
            {
                sr.Close();
                lblError2.Text = "Invalid file header!";
                return;
            }

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "bll_exchrate_import";
            SqlParameter para;
            line = sr.ReadLine();
            while (line != null)
            {
                line_num++;
                line = line.Replace('\t', ',');//将"TAB"替换为","
                try
                {
                    strArray = line.Split(',');
                    if (strArray.Length != 3)
                    {
                        sr.Close();
                        lblError2.Text = "Invalid record! Line:" + line_num.ToString();
                        return;
                    }
                    cmd.Parameters.Clear();
                    para = cmd.Parameters.AddWithValue("@airline", Airline);
                    para = cmd.Parameters.AddWithValue("@exch_from", strArray[0]);
                    para = cmd.Parameters.AddWithValue("@exch_to", strArray[1]);
                    para = cmd.Parameters.AddWithValue("@exch_rate", strArray[2]);
                    para = cmd.Parameters.AddWithValue("@user", User);
                    para = cmd.Parameters.AddWithValue("@ip_addr", IP);
                    ret_code = TinyDAL.Exec(ref cmd);
                    if (ret_code != 0)
                    {
                        sr.Close();
                        lblError2.Text = "Importing failed! Line:" + line_num.ToString() + ", Err:" + ret_code.ToString();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    sr.Close();
                    if (Application["DEBUG"].ToString() == "1")
                        lblError2.Text = ex.Message;
                    else
                        lblError2.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
                    return;
                }

                line = sr.ReadLine();
            }
            sr.Close();
            lblError2.Text = "Done.";
            GridView1.DataBind();
        }
        
    }
}